package ctx

import (
	"context"
	"net"
	"net/http"

	"gitee.com/satyr/tools/conf"
	"gitee.com/satyr/tools/logger"

	"gitee.com/satyr/tools/signal"
)

//Run start
func Run() (err error) {

	//启动http
	address := ""
	if conf.Configuration().Server.Address != "" {
		address = conf.Configuration().Server.Address
	}
	listener, err := net.Listen("tcp", address)
	if err != nil {
		return err
	}
	//logger.Infof("Listening on %s", listener.Addr().String())
	// IP:Port 回塞给配置，确保其地址是完整的
	conf.Configuration().Server.Address = listener.Addr().String()
	server := &http.Server{
		Handler: serveMux,
	}
	go Serve(listener, server)

	// 监听信号
	<-signal.GetSignalContext().Ctx.Done()
	//logger.Info("Shutting down http server...")
	if err := server.Shutdown(context.Background()); err != nil {
		logger.Fatal("Server forced to shutdown:", err)
	}
	<-signal.GetShutdownContext().Ctx.Done()
	//logger.Info("http server stop...")
	return
}

func Serve(listener net.Listener, server *http.Server) (err error) {
	err = server.Serve(listener)
	if err != nil {
		return err
	}
	return nil
}
